#include "PopupConnectionAck.hpp"

using namespace std;
using namespace Popup;

ConnectionAck::ConnectionAck(const Message *p_message,
                             const string & p_resourcePath)
: AbstractMessage(POPUP_MSG_TYPE_CONNECTION_ACK),
  resourcePath(p_resourcePath)
{
  AbstractMessage::deserialize(p_message);
}

bool ConnectionAck::onSend()
{
  bool _rc = AbstractMessage::payloadAddShort(STATUS, status);

  if (status != POPUP_CONNECTION_SUCCESS) {
    return (_rc &&  AbstractMessage::payloadAddString(ERR_MESSAGE,
                                                      errMessage));
  }
  else
  {
    // Add session ID
    if (_rc) {
      _rc = AbstractMessage::payloadAddLong(SESSIONID, sessionID);
    }
    // Add user ID
    if (_rc) {
      _rc = AbstractMessage::payloadAddLong(USERID, user.getID());
    }
    // Add user nickname
    if (_rc) {
      _rc = AbstractMessage::payloadAddString(
          USERNICKNAME, user.getNickname());
    }
    // Add user health status
    if (_rc) {
      _rc = AbstractMessage::payloadAddBoolean(HEALTH, user.isAlive());
    }
    if (_rc)
    {
      // Add avatar (not mandatory!)
      bool _avatarOk = AbstractMessage::payloadAddFileContent(AVATAR_RAW_DATA,
                                                              user.getAvatar());
      if (_avatarOk) {
        AbstractMessage::payloadAddString(AVATAR_FILENAME,
                                          PopupUtils::basename(user.getAvatar()));
      }
    }
    return _rc;
  }
}

bool ConnectionAck::onReceive()
{
  bool _rc = payloadGetShort(STATUS, status);

  if (_rc)
  {
    if (status != POPUP_CONNECTION_SUCCESS) {
      _rc = ((fields.size() == 2) && (payloadGetString(ERR_MESSAGE, errMessage)));
    }
    else
    {
      _rc = (payloadGetLong(SESSIONID, sessionID) &&
             payloadGetLong(USERID, user.id) &&
             payloadGetString(USERNICKNAME, user.nickname),
             payloadGetBoolean(HEALTH, user.alive));
      if (_rc == true) {
        string _avatarFilename;
        if (AbstractMessage::payloadGetString(AVATAR_FILENAME, _avatarFilename)) {
          string _avatarFullpath = resourcePath + "/" + _avatarFilename;
          _rc = AbstractMessage::payloadDumpFieldToFile(AVATAR_RAW_DATA,
                                                        _avatarFullpath);
          if (_rc) {
            user.avatar = _avatarFullpath;
          }
        }
      }
    }
  }
  return _rc;
}
